<template>
  <div id="ctbMap-mapDiv" class="ol-popup">
    <!-- 显示控件 -->
    <div id="ctbMap-setDivPosition"  class="init-setDivPosition">
      <!-- 切换卫星和街道地图 -->
      <p @click="switchMap" class="init-setDivPosition-selected">
        <template v-if="switchMapBool==false">
          <img src="@/assets/map/image/newImage/icon-weixing.png" title="切换卫星地图"><br/><span>卫星图</span>
        </template>
        <template v-else>
          <img src="@/assets/map/image/newImage/icon-weixing.png" title="切换街道地图"><br/><span>街道图</span>
        </template>
      </p>
      <!-- 返回主界面 -->
      <p @click="zoomDefaultPosition" :class="{ 'init-setDivPosition-selected': zoomDefaultPositionBool==true }">
        <img src="@/assets/map/image/newImage/icon-home.png" title="返回主界面"><br/><span>主界面</span>
      </p>
      <!-- 显示工具箱 -->
      <p @click="showHideToolsBoxDiv" :class="{ 'init-setDivPosition-selected': showHideToolsBox==false }">
        <template v-if="showHideToolsBox">
          <img src="@/assets/map/image/newImage/icon-toolbox.png" title="打开工具箱"><br/>
          <span :class="{ 'init-spanBottom': pageType=='' }">工具箱</span>
        </template>
        <template v-else>
          <img src="@/assets/map/image/newImage/icon-toolbox.png" title="关闭工具箱"><br/>
          <span :class="{ 'init-spanBottom': pageType=='' }">工具箱</span>
        </template>
      </p>
      <template v-if="pageType=='地震烈度图绘制页面'">
        <!-- 导入地震影响场 -->
        <p @click="showSeismicInfluenceImport" :class="{ 'init-setDivPosition-selected': showSeismicInfluenceImportBool==true }">
          <img src="@/assets/map/image/newImage/icon-manage.png" title="导入地震影响场"><br/><span>导入</span>
        </p>
        <!-- 制图 -->
        <p @click="showDrawSeismicInfluence"  :class="{ 'init-setDivPosition-selected': showDrawSeismicInfluenceBool==true }">
          <img src="@/assets/map/image/newImage/icon-newTask.png" title="制图"><br/><span>制图</span>
        </p>
        <!-- 烈度说明 -->
        <p @click="showRemark"  :class="{ 'init-setDivPosition-selected': showRemarkBool==true }">
          <img src="@/assets/map/image/newImage/icon-newTask.png" title="烈度说明"><br/><span>烈度说明</span>
        </p>
        <!-- 生成图件 -->
        <p @click="showPrintImage"  :class="{ 'init-setDivPosition-selected': showPrintImageBool==true }">
          <img src="@/assets/map/image/newImage/icon-newTask.png" title="生成图件"><br/><span style="border:0;">生成图件</span>
        </p>
      </template>
    </div>
    <!-- 工具箱 -->
    <div id="ctbMap-ToolsBoxDiv" class="init-ToolsBoxDiv">
      <p @click="measureToolBox" :class="{ 'init-setDivPosition-selected': showHideMeasureTool==false }">
        <template v-if="showHideMeasureTool">
          <img title="开启测量工具" src="@/assets/map/image/cel.png"><br/><span>测量</span>
        </template>
        <template v-else>
          <img title="关闭测量工具" src="@/assets/map/image/cel.png"><br/><span>测量</span>
        </template>
      </p>
      <p @click="positionToolBox" :class="{ 'init-setDivPosition-selected': showHidePositionTool==false }">
        <template v-if="showHidePositionTool">
          <img title="开启定位工具" src="@/assets/map/image/dingw.png"><br/><span style="border:0;">定位</span>
        </template>
        <template v-else>
          <img title="关闭定位工具" src="@/assets/map/image/dingw.png"><br/><span style="border:0;">定位</span>
        </template>
      </p>
    </div>
    <!-- 所有工具 -->
    <div id="ctbMap-AllToolsDiv" class="init-AllToolsDiv">
      <!-- 测量工具 -->
      <div id="ctbMap-MeasureToolsDiv" class="init-AllToolsDivFloat">
        <p @click="measureDistance" :class="{ 'init-setDivPosition-selected': measureDistanceBool==false }">
          <template v-if="measureDistanceBool">
            <img src="@/assets/map/image/jul.png" title="测量距离（在地图上单击鼠标左键绘制折线，双击完成测量）"><br/><span>测量距离</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/jul.png" title="测量距离（在地图上单击鼠标左键绘制折线，双击完成测量）"><br/><span>测量距离</span>
          </template>
        </p>
        <p class="init-AllToolsDiv-split"></p>
        <p @click="measureArea" :class="{ 'init-setDivPosition-selected': measureAreaBool==false }">
          <template v-if="measureAreaBool">
            <img src="@/assets/map/image/mianj.png" title="测量面积（在地图上单击鼠标左键绘制多边形，双击完成测量）"><br/><span>测量面积</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/mianj.png" title="测量面积（在地图上单击鼠标左键绘制多边形，双击完成测量）"><br/><span>测量面积</span>
          </template>
        </p>
        <p class="init-AllToolsDiv-split"></p>
        <p @click="stopMeasure" :class="{ 'init-setDivPosition-selected': stopMeasureBool==false }">
          <template v-if="stopMeasureBool">
            <img src="@/assets/map/image/jshz.png" title="取消测量距离或测量面积操作"><br/><span>结束测量</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/jshz.png" title="取消测量距离或测量面积操作"><br/><span>结束测量</span>
          </template>
        </p>
        <p class="init-AllToolsDiv-split"></p>
        <p @click="clearMeasure" :class="{ 'init-setDivPosition-selected': clearMeasureBool==false }">
          <template v-if="clearMeasureBool">
            <img src="@/assets/map/image/qux.png" title="清空全部测量结果"><br/><span>清空结果</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/qux.png" title="清空全部测量结果"><br/><span>清空结果</span>
          </template>
        </p>
      </div>
      <!-- 定位工具 -->
      <div id="ctbMap-MousePositionDiv">
        <span><img class="init-jingd" src="@/assets/map/image/jingd.png" title="鼠标左键在地图上点击位置的经度值"></span>
        <input id="ctbMap-MousePositionLon" type="text" value="">
        <span><img class="init-weid" src="@/assets/map/image/weid.png" title="鼠标左键在地图上点击位置的纬度值"></span>
        <input id="ctbMap-MousePositionLat" type="text" value="">
        <p @click="clearPosition" :class="{ 'init-setDivPosition-selected': clearPositionBool==false }">
          <template v-if="clearPositionBool">
            <img src="@/assets/map/image/qux.png" title="清空全部定位点图标"><br/><span>清空结果</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/qux.png" title="清空全部定位点图标"><br/><span>清空结果</span>
          </template>
        </p>
        <p class="init-AllToolsDiv-split"></p>
        <p @click="addPosition" :class="{ 'init-setDivPosition-selected': addPositionBool==false }">
          <template v-if="addPositionBool">
            <img src="@/assets/map/image/dingwd.png" title="根据经纬度值在地图上添加定位点图标"><br/><span>添加定位点</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/dingwd.png" title="根据经纬度值在地图上添加定位点图标"><br/><span>添加定位点</span>
          </template>
        </p>
      </div>
    </div>
    <!-- 弹出窗口 -->
    <!--<div id="ctbMap-popup" class="new-ol-popup">
      <a href="#" id="ctbMap-popup-closer" class="new-ol-popup-closer"></a>
      <div id="ctbMap-popup-content"></div>
    </div>-->
    <!--右键菜单-->
    <div id="ctbMap-contextmenu" class="new-popover" style="display:none;">
      <div class="new-triangle"></div>
      <div class="new-contextmenu" v-show="pageType=='地震烈度图绘制页面'">
        <!--任务区域-->
        <p v-show="selectFeatureType=='Polygon' || selectFeatureType=='lineString'" @click="createTaskArea">
          <span>新建任务</span>
        </p>
        <p v-show="selectFeatureType=='taskPolygon'" @click="createTaskArea">
          <span>修改任务</span>
        </p>
        <div v-show="selectFeatureType=='Polygon' || selectFeatureType=='taskPolygon'"></div>
        <!--<p v-show="selectFeatureType=='CircleDraw'" @click="setCircleRadius"><span>设置圆半径</span></p>
        <div v-show="selectFeatureType=='CircleDraw'"></div>-->
        <p v-show="selectFeatureType=='Polygon' || selectFeatureType=='taskPolygon' || selectFeatureType=='lineString'" @click="editDrawGeom">
          <span v-if="editGeomBool==false">开启修改区域</span>
          <span v-else>完成修改区域</span>
        </p>
        <div v-show="selectFeatureType=='Polygon' || selectFeatureType=='taskPolygon'"></div>
        <p  v-show="selectFeatureType=='Polygon' || selectFeatureType=='taskPolygon'" @click="deleteDrawGeom"><span>删除区域</span></p>
        <!--抽样点-->
        <p v-show="selectFeatureType=='sample'" @click="createSamplePoint">
          <span>新建抽样点</span>
        </p>
        <p v-show="selectFeatureType=='taskSample'" @click="createSamplePoint">
          <span>修改抽样点</span>
        </p>
        <div v-show="selectFeatureType=='sample' || selectFeatureType=='taskSample'"></div>
        <p  v-show="selectFeatureType=='sample' || selectFeatureType=='taskSample'" @click="deleteDrawGeom"><span>删除抽样点</span></p>
        <p v-show="selectFeatureType=='drawSeismicInfluence' || selectFeatureType=='drawBezierSplinePolygon'" @click="editDrawInfluence">
          <span v-if="editDrawInfluenceBool==false">开启修改</span>
          <span v-else>完成修改</span>
        </p>
        <p v-show="selectFeatureType=='drawBezierSplinePolygon'" @click="saveDrawInfluence">
          <span>保存等震线</span>
        </p>
        <p v-show="selectFeatureType=='drawBezierSplinePolygon'" @click="deleteDrawInfluence">
          <span>删除</span>
        </p>
        <p v-show="selectFeatureType=='drawSeismicInfluence'" @click="deleteDrawInfluence">
          <span>删除等震线</span>
        </p>
      </div>
    </div>
    <!--设置圆半径-->
    <el-dialog title="设置圆半径" v-model="circleRadiusDialogBool" width="320px" top="200px" append-to-body>
      <div style="padding:20px;">
        <p>
          <span style="font-weight:bold;">半径（米）</span>
          <el-input style="width:170px" v-model="circleRadiusNum" placeholder="请输入半径" clearable />
        </p>
        <p style="text-align: center"><el-button @click="setCircleRadius" type="primary">确定</el-button></p>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/map/ol/ol.css';
import { getProjection,getResolutions,getTiandituVecMap,getTiandituVecText,getTiandituImgMap,getTiandituImgText,
  getRESTLayer,getVectorTileLayer,iServerHttp,meterToDegree,degreeToMeter } from "@/map/projMap.js";
import VectorLayer from 'ol/layer/Vector';
import {Vector as VectorSource} from 'ol/source'
import {Control} from 'ol/control';
// import ScaleLine from 'ol/control/ScaleLine';
import WKT from 'ol/format/WKT';
import GeoJSON from 'ol/format/GeoJSON';
import Overlay from 'ol/Overlay';
import * as turf from "@turf/turf";
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import { MultiPolygon as MultiPolygon2 } from 'ol/geom'
import LineString from 'ol/geom/LineString';
import Circle from 'ol/geom/Circle';
import CircleDraw from 'ol/geom/Circle';
import {fromCircle} from 'ol/geom/Polygon';
import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
import {Select, Draw, Modify, Snap, Translate} from 'ol/interaction';
import {getArea, getLength} from 'ol/sphere';
import {unByKey} from 'ol/Observable';
import {boundingExtent} from 'ol/extent';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';
import { MapService } from '@supermap/iclient-ol';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'

class ModifyConstrain extends Modify {
        constructor(options) {
                super(options);
                this.constrainGeom_ = options.constrainGeom;
        }
        handleDragEvent(evt) {
                if (!this.constrainGeom_.intersectsCoordinate(evt.coordinate))
                        evt.coordinate = this.constrainGeom_.getClosestPoint(evt.coordinate)
                super.handleDragEvent(evt)
        }
}
export default {
  name: "ControlToolBar",
  components: {

  },
  props:{
    map:{//地图对象
      type: Object,
      required:false,
      default: {}
    },
    pageType:{
      type: String,
      required:false,
      default: ""
    },
    mapDrawType: {//是否开启地图圈选查询
      type:String,
      required:false,
      default: ""
    },
    showFileUploadBool:{//是否开启导入影响场按钮
      type: Boolean,
      required: false,
      default: false
    },
    clearSelectFeatureBool:{//是否删除选中要素
      type: Boolean,
      required: false,
      default: false
    },
    outAndInterRingData: {
      type: Array,
      required: true,
      default: []
    },
    showButtonType:{//显示|隐藏按钮类型
      type: String,
      required:false,
      default: ""
    },
  },
  emits:["getAllDrawGeom","seismicInfluenceUpload","createTaskArea","createSamplePoint","openLayerSelect","showRemark","showPrintImage",
    "showDrawSeismicInfluence","getDrawInfluence","deleteDrawInfluence"],
  data() {
    return {
      str: "ctbMap",
      center: [105, 34],
      zoom: 4,
      mapLoadingBool:false,//是否正在查询参数
      zoomDefaultPositionBool:true,//显示主界面
      switchMapBool:false,//切换地图
      layer1:null,//天地图街道图
      layer2:null,
      layer3:null,//天地图卫星图
      layer4:null,
      draw:null,//矢量绘制
      snap:null,
      select:null,
      modify:null,
      drag:null,
      source:null,//矢量绘制图层数据
      measureSource:null,//测量结果图层数据
      measure:null,//测量工具
      sketch:null,
      helpTooltipElement:null,
      helpTooltip:null,
      measureTooltipElement:null,
      measureTooltip:null,
      measureTooltipArray:[],//全部测量结果Overlay数组
      showHideMeasureTool:true,//显示|隐藏测量工具
      measureDistanceBool:true,
      measureAreaBool:true,
      stopMeasureBool:true,
      clearMeasureBool:true,
      showHidePositionTool:true,//显示|隐藏定位工具
      addPositionBool:true,
      clearPositionBool:true,
      popupInfoLayer:null,//弹出窗口
      showHideToolsBox:true,
      //addressMatchService:null,//地址匹配
      addressUrl:"https://iserver.supermap.io/iserver/services/addressmatch-Address/restjsr/v1/address",
      selectFeature:null,//选中要素
      //地震烈度图绘制页面
      showSeismicInfluenceImportBool:false,//是否打开导入地震影响场按钮
      showDrawSeismicInfluenceBool:false,//是否打开制图按钮
      showRemarkBool:false,//是否打开烈度说明按钮
      showPrintImageBool:false,//是否打开生成图件按钮
      showCreateTaskAreaBool:false,//是否打开新建任务（划定评估子区）按钮
      showSamplePointBool:false,//是否打开新建抽样点按钮
      showButtonTypeStr:"",//显示按钮类型
      queryMapDrawType:"",//是否开启地图圈选参数（StopDraw关闭地图圈选 Polygon多边形绘制 Circle圆形绘制 Clear清空 GetAll获取全部）
      initBool:false,//是否完成初始化工具条控件
      contextmenuLayer:null,//右键弹出窗口
      selectFeatureType:null,//选择的空间数据类型
      circleRadiusNum:0,//设置圆半径（米）
      circleRadiusDialogBool:false,//是否显示设置圆半径弹窗
      editGeomBool:false,//是否开启修改空间数据
      restricTionSource: null,
      outAndInterRingDataSelf: [],
      index: 0,
      createTaskDataLayer: null,
      lineStringList: [],
      editDrawInfluenceBool:false,//是否开启修改等震线
      drawInfluenceSource:null,//等震线绘制图层数据
      drawBezierSplinePolygonIntensity:null,//绘制地震烈度图烈度
    }
  },
  watch: {
    map: {//地图对象
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          console.log("地图对象");
          console.log(newVal);
          //初始化地图基础数据组件信息
          this.initMap();
        }
      },
      immediate:true
    },
    mapDrawType: {//是否开启地图圈选查询
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          console.log("是否开启地图圈选查询"+newVal);
          this.queryMapDrawType = newVal;
          this.queryMapEvent();
        }
      },
      immediate:true
    },
    showFileUploadBool:{//是否开启导入影响场按钮
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          console.log("是否开启导入影响场按钮"+newVal);
          this.showSeismicInfluenceImportBool = newVal;
        }
      },
      immediate:true
    },
    clearSelectFeatureBool:{//是否删除选中要素
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          console.log("是否删除选中要素"+newVal);
          if(newVal){
            this.clearSelectFeature();//删除选中要素
          }
        }
      },
      immediate:true
    },
    outAndInterRingData: {
      handler: function(newVal,oldVal) {
        this.outAndInterRingDataSelf = newVal
        this.drawLineString(this.outAndInterRingDataSelf)
      },
      immediate: true
    },
    showButtonType:{//显示|隐藏按钮类型
      handler: function(newVal,oldVal) {
        this.showHideButtonType(newVal);
      },
      immediate: true
    },
  },
  mounted() {
    console.log("mounted地图基础数据组件异步加载");
    let that = this;
    //地图基础数据组件异步加载
    this.$nextTick(function(){
      console.log('地图基础数据组件异步加载');
      //地图基础数据组件异步加载
      setTimeout(() => {
        //初始化地图基础数据组件信息
        that.initMap();
      }, 200);
    });
  },
  methods: {
    initMap() {
      if(this.map!=null && this.map.getSize()!=null){
        if(this.initBool){//是否完成初始化工具条控件
          return;
        }
        console.log('initMap地图基础数据组件异步加载');
        let that = this;
        let mapStr = this.str;
        //新建popup弹窗
        let targetDiv = document.getElementById(mapStr+"-mapDiv");
        let node = document.createElement("div");
        node.id = mapStr+"-popup";
        node.setAttribute("class","new-ol-popup");
        node.innerHTML = '<a href="#" id="'+mapStr+'-popup-closer" class="new-ol-popup-closer"></a>' +
            '<div id="'+mapStr+'-popup-content"></div>';
        targetDiv.appendChild(node);
        console.log("新建popup");

        //添加天地图图层
        this.layer1 = getTiandituVecMap();//fxpc天地图街道影像底图
        this.map.addLayer(this.layer1);
        this.layer2 = getTiandituVecText();//fxpc天地图街道地图注记
        this.map.addLayer(this.layer2);
        this.layer1.setZIndex(0);
        this.layer2.setZIndex(0);
        //矢量绘制图层
        this.source = new VectorSource({
          wrapX: false
        });
        let vectorLayer = new VectorLayer({
          source: that.source,
          projection: 'EPSG:4490'
        });
        this.map.addLayer(vectorLayer);
        vectorLayer.setZIndex(1);
        //测量结果图层
        this.measureSource = new VectorSource({
          wrapX: false
        });
        let measureLayer = new VectorLayer({
          source: that.measureSource,
          projection: 'EPSG:4490'
        });
        this.map.addLayer(measureLayer);
        measureLayer.setZIndex(1);

        //任务空间数据图层
        this.createTaskDataLayer = new VectorLayer({
          source: new VectorSource({
            wrapX: false
          }),
          projection: 'EPSG:4490'
        });
        this.map.addLayer(this.createTaskDataLayer);
        this.createTaskDataLayer.setZIndex(1);

        //地震烈度图等震线绘制图层
        this.drawInfluenceSource = new VectorSource({
          wrapX: false
        });
        let drawInfluenceLayer = new VectorLayer({
          source: that.drawInfluenceSource,
          projection: 'EPSG:4490'
        });
        this.map.addLayer(drawInfluenceLayer);
        drawInfluenceLayer.setZIndex(10);

        //添加控件
        let info = new Control({element: document.getElementById(mapStr+'-mapDiv')});
        info.setMap(this.map);
        this.map.addControl(info);
        //比例尺控件
        // let scaleControl = new ScaleLine();
        // this.map.addControl(scaleControl);
        //弹出窗口
        let popupTarget = document.getElementById(this.str+"-popup");
        if(popupTarget){
          this.popupInfoLayer = new Overlay({
            element: popupTarget,
            positioning: 'center-center'
          });
          this.map.addOverlay(this.popupInfoLayer);
          //显示弹出窗口
          document.getElementById(this.str+"-popup").style.display="block";
          //关闭弹出事件
          document.getElementById(this.str+"-popup-closer").onclick = function () {
            that.popupInfoLayer.setPosition(undefined);
            //隐藏弹出窗口
            document.getElementById(that.str+"-popup").style.display="none";
          };
        }
        //右键菜单弹出窗口
        let contextmenuTarget = document.getElementById(this.str+"-contextmenu");
        if(contextmenuTarget){
          this.contextmenuLayer = new Overlay({
            element: contextmenuTarget,
            positioning: 'center-center'
          });
          this.map.addOverlay(this.contextmenuLayer);
          //显示右键菜单
          document.getElementById(that.str+"-contextmenu").style.display="block";
        }
        //右键菜单事件
        this.map.on('contextmenu', function(event){
          event.preventDefault();//屏蔽自带的右键事件
          let pixel = that.map.getEventPixel(event.originalEvent);
          let coordinate = that.map.getEventCoordinate(event.originalEvent);
          that.contextmenuLayer.setPosition(undefined);
          let feature = that.map.forEachFeatureAtPixel(pixel,function(feature){
            //根据像素坐标获取右键选中的地图要素
            return feature;
          });
          that.selectFeatureType = 'lineString'
          if(feature && that.draw==null){
            let temp = feature.getProperties();
            if(that.pageType=='地震烈度图绘制页面'){
              if(temp.type=="draw"){//地图圈选
                let geometry = feature.getGeometry();
                if (geometry instanceof Polygon || geometry instanceof MultiPolygon2) {
                  that.selectFeatureType = "Polygon";
                }else if (geometry instanceof CircleDraw) {
                  that.selectFeatureType = "CircleDraw";
                }
                //显示右键菜单
                that.contextmenuLayer.setOffset([10,-30]);
                that.contextmenuLayer.setPosition(coordinate);
              }else if(temp.type=="drawSeismicInfluence"){//地震烈度图
                that.selectFeatureType = "drawSeismicInfluence";
                //显示右键菜单
                that.contextmenuLayer.setOffset([10,-30]);
                that.contextmenuLayer.setPosition(coordinate);
              }else if(temp.type=="taskPolygon"){//保存的任务区域
                that.selectFeatureType = "taskPolygon";
                //显示右键菜单
                that.contextmenuLayer.setOffset([10,-30]);
                that.contextmenuLayer.setPosition(coordinate);
              }else if(temp.type=="taskSample"){//保存的抽样点
                that.selectFeatureType = "taskSample";
                //显示右键菜单
                that.contextmenuLayer.setOffset([10,-30]);
                that.contextmenuLayer.setPosition(coordinate);
              }else if(temp.type=="sample"){//绘制的抽样点
                let geometry = feature.getGeometry();
                if (geometry instanceof Point) {
                  that.selectFeatureType = "sample";
                }
                //显示右键菜单
                that.contextmenuLayer.setOffset([10,-30]);
                that.contextmenuLayer.setPosition(coordinate);
              }else if(temp.type=="drawBezierSplinePolygon"){//绘制的地震烈度图
                that.selectFeatureType = "drawBezierSplinePolygon";
                //显示右键菜单
                that.contextmenuLayer.setOffset([10,-30]);
                that.contextmenuLayer.setPosition(coordinate);
              }
            }
            //选中要素
            that.selectFeature = feature;
          }
        });
        //点击地图事件
        this.map.on('click', function(event){
          //隐藏右键菜单
          that.hideContextMenu();
          //隐藏弹出窗口
          if(that.popupInfoLayer!=null){
            that.popupInfoLayer.setPosition(undefined);
          }
          //隐藏右键菜单窗口
          if(that.contextmenuLayer!=null){
            that.contextmenuLayer.setPosition(undefined);
          }
          let pixel = that.map.getEventPixel(event.originalEvent);
          let coordinate = that.map.getEventCoordinate(event.originalEvent);
          //判断定位工具是否开启状态
          if(that.showHidePositionTool==false){
            document.getElementById(mapStr+"-MousePositionLon").value = coordinate[0];
            document.getElementById(mapStr+"-MousePositionLat").value = coordinate[1];
          }

          let feature = that.map.forEachFeatureAtPixel(pixel,function(feature){
            //根据像素坐标获取右键选中的地图要素
            return feature;
          });
          if(feature && that.draw==null){
            let temp = feature.getProperties();
            console.log(temp);
            if(that.pageType=='地震烈度图绘制页面'){
              if(temp.type=="draw"){//地图圈选
                let geometry = feature.getGeometry();
                if (geometry instanceof Polygon) {
                  that.selectFeatureType = "Polygon";
                }else if (geometry instanceof CircleDraw) {
                  that.selectFeatureType = "CircleDraw";
                }
              }else if(temp.type=="taskPolygon"){//保存的任务区域
                that.selectFeatureType = "taskPolygon";
                let xstmId = "";
                if (temp.xstmId!=undefined) {
                  xstmId = temp.xstmId;
                }
                if(that.editGeomBool==false){
                  //获取选中的要素空间数据
                  that.$emit("createTaskArea",{type:"查看",xstmId:xstmId});
                }
              }else if(temp.type=="taskSample"){//保存的抽样点
                that.selectFeatureType = "taskSample";
                let id = "";
                if (temp.id!=undefined) {
                  id = temp.id;
                }
                if(that.editGeomBool==false){
                  //获取选中的要素空间数据
                  that.$emit("createSamplePoint",{type:"查看",id:id});
                }
              }else if(temp.type=="sample"){//绘制的抽样点
                let geometry = feature.getGeometry();
                if (geometry instanceof Point) {
                  that.selectFeatureType = "sample";
                }
              }else if(temp.type=="aftershockSequence"){//余震序列
                let geometry = feature.getGeometry();
                if (geometry instanceof Point) {
                  that.selectFeatureType = "aftershockSequence";
                  let props = temp.props;
                  let date = new Date(props.time);
                  //获取发震时间，格式YYYY-MM-DD HH:mm:ss
                  let time = that.getFormatTime(date);
                  let html = `发震时间：${time}<br/>震级：${props.mm}<br/>震源深度：${props.epiDepth} km<br/>震中位置：${props.location}<br/>省：${props.province}<br/>市：${props.city}<br/>县：${props.county}`;
                  //设置弹窗内容
                  that.setPopupContent(html);
                  console.log(html)
                  that.popupInfoLayer.setPosition(coordinate);
                }
              }
            }
            //选中要素
            that.selectFeature = feature;
          }
        });
        //地图移动事件
        this.map.on('moveend', function (event) {
          let center = that.map.getView().getCenter();
          let zoom = that.map.getView().getZoom();
          if(center[0]!=that.center[0] || center[1]!=that.center[1] || zoom!=that.zoom){
            //设置主界面图标文字
            that.zoomDefaultPositionBool = false;
          }else{//主界面
            //设置主界面图标文字
            that.zoomDefaultPositionBool = true;
          }
        });
        //鼠标移动事件--测量工具
        this.map.on('pointermove', function (evt) {
          if (evt.dragging) {
            return;
          }
          if(that.measure!=null){
            let helpMsg = '点击开始绘制';

            if (that.sketch) {
              const geom = that.sketch.getGeometry();
              if (geom instanceof Polygon) {
                helpMsg = '点击继续绘制多边形';
              } else if (geom instanceof LineString) {
                helpMsg = '点击继续绘制折线';
              }
            }

            that.helpTooltipElement.innerHTML = helpMsg;
            that.helpTooltip.setPosition(evt.coordinate);

            that.helpTooltipElement.classList.remove('hidden');
          }
        });
        //鼠标移出事件--测量工具
        this.map.getViewport().addEventListener('mouseout', function () {
          if(that.measure!=null){
            that.helpTooltipElement.classList.add('hidden');
          }
        });
        //地址匹配
        //this.addressMatchService = new AddressMatchService(this.addressUrl);
        //地图缩放到权限位置
        this.zoomDefaultPosition();

        //是否完成初始化工具条控件
        this.initBool = true;
      }
    },
    drawLineString(list) {
      if (list.length != 0 && list[0] != false) {
        console.log(list[2].getCoordinates())
        console.log(list[3].getCoordinates())
        this.lineStringList[0] = list[2].getCoordinates()
        this.lineStringList[1] = list[3].getCoordinates()
        let feature = new Feature(list[2])
        feature.setProperties({
          type:"draw",//类型
          xstmId: list[4].xstmId
        });
        feature.setStyle(this.getLineStringStyle('red'))
        this.createTaskDataLayer.getSource().addFeature(feature);
        let feature2 = new Feature(list[3])
        feature2.setProperties({
          type:"draw",//类型
          xstmId: list[4].xstmId
        });
        feature2.setStyle(this.getLineStringStyle('red'))
        this.createTaskDataLayer.getSource().addFeature(feature2);
      }else if(list[0] == false) {
        this.createTaskDataLayer.getSource().clear()
      }
    },
    autodivheight() {//自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:864px,地图div高度:754px
      let tempHeight = 864;
      let mapTempHeight = 754;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      //最小高度
      if(mapHeight<480){
        mapHeight = 480;
      }
      //设置地图高度
      document.getElementById(this.str+"-map").style.height= mapHeight +"px";
      console.log("窗口高度："+winHeight+"地图高度："+mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if(this.map){
        this.map.updateSize();
        console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
    setPopupContent(html){//设置弹窗内容
      document.getElementById(this.str+'-popup-content').innerHTML = html;
      //显示弹出窗口
      document.getElementById(this.str+"-popup").style.display="block";
    },
    getTextFormat(str){//格式化文本内容
      if(str==null || str==undefined){
        str = "";
      }
      return str;
    },
    hideContextMenu(){//隐藏右键菜单
      //隐藏右键菜单

    },
    //切换地图
    switchMap(){
      if(this.switchMapBool){//显示街道图
        this.switchMapBool = false;
        //添加天地图图层
        if(this.layer1==null){
          this.layer1 = getTiandituVecMap();//fxpc天地图街道影像底图
          this.map.addLayer(this.layer1);
        }
        if(this.layer2==null){
          this.layer2 = getTiandituVecText();//fxpc天地图街道地图注记
          this.map.addLayer(this.layer2);
        }
        //显示街道图
        this.layer1.setVisible(true);
        this.layer2.setVisible(true);
        this.layer3.setVisible(false);
        this.layer4.setVisible(false);
        this.layer1.setZIndex(0);
        this.layer2.setZIndex(0);
      }else{//显示卫星图
        this.switchMapBool = true;
        if(this.layer3==null){
          this.layer3 = getTiandituImgMap();//fxpc天地图卫星影像底图
          this.map.addLayer(this.layer3);
        }
        if(this.layer4==null){
          this.layer4 = getTiandituImgText();//fxpc天地图卫星影像注记
          this.map.addLayer(this.layer4);
        }
        //显示卫星图
        this.layer1.setVisible(false);
        this.layer2.setVisible(false);
        this.layer3.setVisible(true);
        this.layer4.setVisible(true);
        this.layer3.setZIndex(0);
        this.layer4.setZIndex(0);
      }
    },
    //地图缩放到权限位置
    zoomDefaultPosition() {
      //刷新地图,确保地图不变形
      this.map.updateSize();
      this.map.getView().setCenter(this.center);
      this.map.getView().setZoom(this.zoom);
      this.zoomDefaultPositionBool = true;
    },
    //显示工具箱
    showHideToolsBoxDiv(){
      if(this.showHideToolsBox){
        this.showHideToolsBox = false;
        document.getElementById(this.str+"-ToolsBoxDiv").style.display="block";
      }else{
        this.showHideToolsBox = true;
        document.getElementById(this.str+"-ToolsBoxDiv").style.display="none";
      }
      //关闭全部工具
      this.closeAllToolsBox(null);
    },
    //关闭全部工具
    closeAllToolsBox(type){
      //关闭测量工具
      if(type!="MeasureTool" && this.showHideMeasureTool==false){
        this.showHideMeasureTool = true;
        let divId = this.str+"-MeasureToolsDiv";
        //隐藏
        document.getElementById(divId).style.display = "none";
        //清空测量结果
        this.clearMeasure();
        this.clearMeasureBool = true;
      }
      //关闭定位工具
      if(type!="PositionTool" && this.showHidePositionTool==false){
        this.showHidePositionTool = true;
        let divId = this.str+"-MousePositionDiv";
        //隐藏
        document.getElementById(divId).style.display = "none";
        //清空定位结果
        this.clearPosition();
      }
    },
    //地图工具--测试地图打印功能
    toolsBoxPrintTest(){
      let that = this;
      //测试地图导出方法一
      /*this.map.once('rendercomplete', function () {
        const mapCanvas = document.createElement('canvas');
        const size = that.map.getSize();
        mapCanvas.width = size[0];
        mapCanvas.height = size[1];
        const mapContext = mapCanvas.getContext('2d');
        Array.prototype.forEach.call(
            //document.querySelectorAll('.ol-layer canvas'),
            document.querySelectorAll('#ctbMap-map .ol-viewport .ol-layer canvas'),
            function (canvas) {
              if (canvas.width > 0) {
                const opacity = canvas.parentNode.style.opacity;
                mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
                const transform = canvas.style.transform;
                // Get the transform parameters from the style's transform matrix
                const matrix = transform
                    .match(/^matrix\(([^\(]*)\)$/)[1]
                    .split(',')
                    .map(Number);
                // Apply the transform to the export map context
                CanvasRenderingContext2D.prototype.setTransform.apply(
                    mapContext,
                    matrix
                );
                mapContext.drawImage(canvas, 0, 0);
              }
            }
        );
        if (navigator.msSaveBlob) {
          // link download attribute does not work on MS browsers
          navigator.msSaveBlob(mapCanvas.msToBlob(), 'map.png');
        } else {
          const link = document.getElementById('image-download');
          link.crossOrigin = 'anonymous';
          link.href = mapCanvas.toDataURL();
          link.click();
        }
      });
      this.map.renderSync();*/


      //测试地图导出方法二
      /*let exportPNGElement = document.getElementById('export-png'); //导出图片功能项
      let manypng = document.getElementById('manypng'); //导出图片功能项
      if ('download' in exportPNGElement) {
        exportPNGElement.addEventListener('click', function (e) {
          that.map.once('postcompose', function (event) {
            let canvas = event.context.canvas; //地图渲染容器
            exportPNGElement.href = canvas.toDataURL('image/png'); //导出图片
          });
          that.map.renderSync();
        }, false);
      } else {
        alert("浏览器不支持此导出地图图片功能！");
      }

      if ('download' in manypng) {
        manypng.addEventListener('click', function(e) {
          //  that.map.removeInteraction(draw);
          addInteraction();
          that.map.renderSync();
        },false);
      }

      let draw; // global so we can remove it later
      let source = new VectorSource();
      function addInteraction() {
        draw = new Draw({
          source: source,
          type: 'LineString',
          style: new Style({
            fill: new Fill({
              color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new Stroke({
              color: '#ffcc33',
              width: 2
            }),
            image: new CircleStyle({
              radius: 7,
              fill: new Fill({
                color: '#ffcc33'
              })
            })
          }),
          maxPoints: 2,
          geometryFunction: createBox()//矩形框
        })

        that.map.addInteraction(draw);

        // that.map.values_.target='map2';

        function getXDis(e, number) {
          let min = undefined;
          let max = undefined;
          e.forEach(element => {
            if (min == undefined || element[number] < min) {
              min = element[number];
            }

            if (max == undefined || element[number] > max) {
              max = element[number];
            }
          });
          return [min+2, max - min-4];
        }

        let extent = [];
        draw.on('drawend',function(evt){
          let feature = evt.feature;console.log(feature);
          let ftarget = evt.target.a;
          let geometry=feature.getGeometry();
          let ext=geometry.getExtent();
          that.map.removeInteraction(draw);

          let r = that.map.getView().getResolutionForExtent(ext, that.map.getSize());//根据范围获取分辨率
          that.map.getView().setResolution(r);
          that.map.getView().setZoom(12);
          let centerone=olExtent.getCenter(ext);
          that.map.getView().setCenter(centerone);

          let canvas;
          let imageData;
          let canvas2;
          let coordinate=geometry.getCoordinates();
          that.map.once("postrender", function (e) {
            extent[0] = e.target.getPixelFromCoordinate(coordinate[0][0]);//转画布坐标
            extent[1] = e.target.getPixelFromCoordinate(coordinate[0][1]);
            extent[2] = e.target.getPixelFromCoordinate(coordinate[0][2]);
            extent[3] = e.target.getPixelFromCoordinate(coordinate[0][3]);

            let x_dx = getXDis(extent, 0);
            let y_dy = getXDis(extent, 1);

            that.map.once("postcompose", function(event) {
              canvas = event.context.canvas;
              let ctx2=canvas.getContext("2d");
              imageData = ctx2.getImageData(x_dx[0], y_dy[0], x_dx[1], y_dy[1]);
              let c=document.getElementById("ctbMap-map");
              c.style.width=imageData.width+'px';
              c.style.height=imageData.height+'px';
              that.map.updateSize();//容器改变重新加载地图
            });
            that.map.once('rendercomplete',function(){//渲染完成
              canvas.toBlob(function (blob) {
                saveAs(blob, 'map.png');
                $('#ctbMap-map').css({
                  width:"100%",
                  height:"100%"
                });
                that.map.updateSize();//容器改变重新加载地图
              });
            });
          });
        });
      }*/
    },
    measureToolBox(){//测量工具Div
      let divId = this.str+"-MeasureToolsDiv";
      //关闭全部工具
      this.closeAllToolsBox("MeasureTool");
      if(this.showHideMeasureTool){
        this.showHideMeasureTool = false;
        //显示
        document.getElementById(divId).style.display = "block";
      }else{
        this.showHideMeasureTool = true;
        //隐藏
        document.getElementById(divId).style.display = "none";
      }
    },
    measureDistance(){//测距
      if(this.source!=null){
        //地图工具箱--开启测距
        this.setMapToolBox('MeasureDistance');
        //设置样式
        this.measureDistanceBool = false;
        this.measureAreaBool = true;
        this.stopMeasureBool = true;
        this.clearMeasureBool = true;
      }
    },
    measureArea(){//测面
      if(this.source!=null){
        //地图工具箱--开启测面
        this.setMapToolBox('MeasureArea');
        //设置样式
        this.measureAreaBool = false;
        this.measureDistanceBool = true;
        this.stopMeasureBool = true;
        this.clearMeasureBool = true;
      }
    },
    stopMeasure(){//停止测量
      if(this.source!=null){
        //地图工具箱--停止测量
        this.setMapToolBox('StopMeasure');
        //设置样式
        this.stopMeasureBool = false;
        this.measureDistanceBool = true;
        this.measureAreaBool = true;
        this.clearMeasureBool = true;
      }
    },
    clearMeasure(){//清空测量结果
      if(this.source!=null){
        //地图工具箱--清空测量结果
        this.setMapToolBox('ClearMeasure');
        //设置样式
        this.clearMeasureBool = false;
        this.measureDistanceBool = true;
        this.measureAreaBool = true;
        this.stopMeasureBool = true;
      }
    },
    positionToolBox(){//定位工具Div
      let divId = this.str+"-MousePositionDiv";
      //关闭全部工具
      this.closeAllToolsBox("PositionTool");
      if(this.showHidePositionTool){
        this.showHidePositionTool = false;
        //显示
        document.getElementById(divId).style.display = "block";
      }else{
        this.showHidePositionTool = true;
        //隐藏
        document.getElementById(divId).style.display = "none";
      }
    },
    addPosition(){//添加定位结果
      this.clearPositionBool = true;
      this.addPositionBool = false;
      //添加定位结果
      if(this.source!=null){
        let longitude = document.getElementById(this.str+"-MousePositionLon").value;
        let latitude = document.getElementById(this.str+"-MousePositionLat").value;
        //处理经纬度
        let lonlat = this.getLonLat(longitude,latitude);
        if(lonlat!=null){
          //点
          let featureTmp = new Feature({
            geometry: new Point(lonlat)
          });
          //样式
          let style = this.getPointStyle();
          featureTmp.setStyle(style);
          //设置属性
          featureTmp.setProperties({
            type:"position",
            longitude:longitude,
            latitude:latitude,
          });
          //添加定位点
          this.source.addFeature(featureTmp);
          //居中缩放
          this.map.getView().setCenter(lonlat);
          this.map.getView().setZoom(12);
        }
      }
    },
    clearPosition(){//清空定位结果
      this.clearPositionBool = false;
      this.addPositionBool = true;
      //地图工具箱--清空
      this.setMapToolBox("Clear");
    },
    //地图工具箱
    setMapToolBox(value){
      let that = this;
      if (value === 'Clear') {//清空
        //清空
        that.source.clear();
        //停止绘制|修改|拖拽|选择
        clearInteraction();
      }else if (value === 'clearBezierSplinePolygon') {//清空绘制贝塞尔曲线面
        //清空
        that.drawInfluenceSource.clear();
        //停止绘制|修改|拖拽|选择--等震线贝塞尔曲线面
        clearNewInteraction();
      }else if (value === 'BezierSplinePolygon') {//开启绘制贝塞尔曲线面
        //开启绘制--等震线贝塞尔曲线面
        startNewDrawInteraction('Polygon',false);
      }else if (value === 'StopDrawBezierSplinePolygon') {//停止绘制贝塞尔曲线面
        //停止绘制--等震线贝塞尔曲线面
        stopNewDrawInteraction();
      }else if (value === 'Point' || value === 'LineString' || value === 'Polygon' || value === 'Circle') {//开启绘制
        //点|线|面|圆绘制
        //开启绘制
        startDrawInteraction(value,false);
      }else if (value === 'CircleRadius') {//开启绘制圆心，输入半径生成圆
        //开启绘制圆心点
        startDrawInteraction("Point",false);
      }else if (value === 'FreeHandLineString' || value === 'FreeHandPolygon') {//开启绘制
        //手绘线|手绘面
        value = value.split("FreeHand")[1];
        //开启绘制
        startDrawInteraction(value,true);
      }else if (value === 'StopDraw') {//停止绘制
        //停止绘制
        stopDrawInteraction();
      }else if (value === 'Snap') {//开启捕捉
        //开启捕捉
        startSnapInteraction();
      }else if (value === 'NotSnap') {//停止捕捉
        //停止捕捉
        stopSnapInteraction();
      }else if (value === 'Modify') {//开启修改
        //开启修改
        startModifyInteraction();
      }else if (value === 'NotModify') {//停止修改
        //停止修改
        stopModifyInteraction();
        //停止选择
        stopSelectInteraction();
      }else if (value === 'Drag') {//开启拖拽
        //开启拖拽
        startDragInteraction();
      }else if (value === 'NotDrag') {//停止拖拽
        //停止拖拽
        stopDragInteraction();
      }else if (value === 'Select') {//开启选择
        //开启选择
        startSelectInteraction();
      }else if (value === 'NotSelect') {//停止选择
        //停止选择
        stopSelectInteraction();
      } else if (value === 'MeasureDistance') {//开启测距
        //开启测距
        startMeasureInteraction('LineString');
      } else if (value === 'MeasureArea') {//开启测面
        //开启测面
        startMeasureInteraction('Polygon');
      } else if (value === 'StopMeasure') {//停止测量（测距|测面）
        //停止测量
        stopMeasureInteraction();
      } else if (value === 'ClearMeasure') {//清空测量结果
        //停止测量
        stopMeasureInteraction();
        //清空测量结果
        clearMeasureResult();
      }else if (value === 'NewModify') {//开启修改--等震线贝塞尔曲线面
        //开启修改
        startNewModifyInteraction();
      }else if (value === 'StopNewModify') {//停止修改--等震线贝塞尔曲线面
        //停止修改
        stopNewModifyInteraction();
        //停止选择
        stopSelectInteraction();
      }

      //停止绘制|修改|拖拽|选择
      function clearInteraction() {
        //停止拖拽
        stopDragInteraction();
        //停止修改
        stopModifyInteraction();
        //停止选择
        stopSelectInteraction();
        //停止绘制
        stopDrawInteraction();
      }

      //停止捕捉
      function stopSnapInteraction(){
        if (that.snap) {
          that.map.removeInteraction(that.snap);
          that.snap = null;
        }
      }

      //开启捕捉
      function startSnapInteraction(){
        //停止捕捉
        stopSnapInteraction();
        //开启捕捉
        that.snap = new Snap({
          source: that.source,
          edge: true,
          vertex: true,
        });
        that.map.addInteraction(that.snap);
      }

      //停止拖拽
      function stopDragInteraction() {
        //停止拖拽
        if (that.drag) {
          that.map.removeInteraction(that.drag);
          that.drag = null;
        }
      }

      //开启拖拽
      function startDragInteraction() {
        //停止绘制
        stopDrawInteraction();
        //停止修改
        stopModifyInteraction();
        //开启选择
        startSelectInteraction();
        //停止拖拽
        stopDragInteraction();
        //开启拖拽
        that.drag = new Translate({
          features: that.select.getFeatures(),
        });
        that.map.addInteraction(that.drag);
      }

      //停止修改
      function stopModifyInteraction() {
        //停止修改
        if (that.modify) {
          that.map.removeInteraction(that.modify);
          that.modify = null;
          if(that.pageType=='地震烈度图绘制页面'){
            //获取绘制数据
            // that.getAllDrawGeomEmit();
          }
        }
      }

      //开启修改
      function startModifyInteraction() {
        //停止绘制
        stopDrawInteraction();
        //开启选择
        startSelectInteraction();
        //停止修改
        stopModifyInteraction();
        //开启修改
        that.modify = new ModifyConstrain({
          features: that.select.getFeatures(),
          constrainGeom: that.restricTionSource.getGeometry()
        });
        that.map.addInteraction(that.modify);
        that.modify.on('modifystart', function (evt) {
          that.index = 0
          for(let i = 0;i < that.outAndInterRingDataSelf.length;i++) {
            if( i == 2 || i == 3) {
              let featureCoor = that.outAndInterRingDataSelf[i].getCoordinates()
              let selectFeatureCoor = evt.features.array_[0].values_.geometry.getCoordinates()
              if(featureCoor[0][0] == selectFeatureCoor[0][0]) {
                that.index = i
              }
            }
          }
          console.log('开始:' + that.index)
        })
        that.modify.on('modifyend', function (evt) {
          console.log('结束:' + that.index)
          let coor = evt.features.array_[0].values_.geometry.getCoordinates()
          let lineStringList = []
          for(let i = 0;i < coor.length;i++) {
            lineStringList.push(coor[i])
          }
          let linString = new LineString(lineStringList)
          if (that.lineStringList[0][0][0] == coor[0][0] && that.lineStringList[0][0][1]== coor[0][1] && that.lineStringList[0][that.lineStringList[0]. length -1][0] == coor[coor.length -1][0] && that.lineStringList[0][that.lineStringList[0]. length -1][1] == coor[coor.length -1][1] && that.index == 2) {
            that.outAndInterRingDataSelf[that.index] = linString
            that.lineStringList[0] = coor
          }else if(that.lineStringList[1][0][0] == coor[0][0] && that.lineStringList[1][0][1]== coor[0][1] && that.lineStringList[1][that.lineStringList[1]. length -1][0] == coor[coor.length -1][0] && that.lineStringList[1][that.lineStringList[1]. length -1][1] == coor[coor.length -1][1] && that.index == 3) {
            that.outAndInterRingDataSelf[that.index] = linString
            that.lineStringList[1] = coor
          }
          else{
            that.createTaskDataLayer.getSource().clear()
            let temp = that.lineStringList[0]
            let pointList = []
            for(let i = 0;i < temp.length;i++) {
              pointList.push(temp[i])
            }
            let feature = new Feature({
              geometry: new LineString(pointList)
            })
            let temp1 = that.lineStringList[1]
            let pointList1 = []
            for(let i = 0;i < temp1.length;i++) {
              pointList1.push(temp1[i])
            }
            let feature1 = new Feature({
              geometry: new LineString(pointList1)
            })
            feature.setProperties({
              type:"draw",//类型
              xstmId: that.outAndInterRingDataSelf[4].xstmId
            });
            feature.setStyle(that.getLineStringStyle('red'))
            that.createTaskDataLayer.getSource().addFeature(feature);
            feature1.setProperties({
              type:"draw",//类型
              xstmId: that.outAndInterRingDataSelf[4].xstmId
            });
            feature1.setStyle(that.getLineStringStyle('red'))
            that.createTaskDataLayer.getSource().addFeature(feature1);
            that.$message('不能修改初始点，请重新选择！')
          }
          
        })
      }

      //停止选择
      function stopSelectInteraction() {
        //停止选择
        if (that.select) {
          that.map.removeInteraction(that.select);
          that.select = null;
        }
      }

      //开启选择
      function startSelectInteraction() {
        //停止选择
        stopSelectInteraction();
        //开启选择
        that.select = new Select({
          wrapX: false,
          filter:(feature, layer)=>{
            //过滤可选择的要素
            let temp = feature.getProperties();
            if(that.pageType=='地震烈度图绘制页面') {
              if (temp.type == "draw" || temp.type == "taskPolygon" || temp.type=="drawBezierSplinePolygon") {//地图圈选|任务区域|绘制贝塞尔曲线面
                return true;
              }
            }
            return false;
          }
        });
        that.map.addInteraction(that.select);
      }

      //停止绘制
      function stopDrawInteraction() {
        //停止绘制
        if (that.draw) {
          that.map.removeInteraction(that.draw);
          that.draw = null;
        }
      }

      //开启绘制
      function startDrawInteraction(type,bool) {
        //停止拖拽
        stopDragInteraction();
        //停止修改
        stopModifyInteraction();
        //停止选择
        stopSelectInteraction();
        //停止绘制
        stopDrawInteraction();
        if(bool){//手绘线|手绘面
          that.draw = new Draw({
            source: that.source,
            type: type,
            snapTolerance: 20,
            freehand: true
          });
          that.map.addInteraction(that.draw);
        }else{//点|线|面|圆绘制
          that.draw = new Draw({
            source: that.source,
            type: type,
            snapTolerance: 20
          });
          that.map.addInteraction(that.draw);
        }
        //完成绘制事件
        that.draw.on('drawend', function (evt) {
          if(that.pageType=='地震烈度图绘制页面'){
            //是否开启地图圈选查询
            if(that.queryMapDrawType=="Polygon" || that.queryMapDrawType=="Circle"){
              evt.feature.setProperties({
                type:"draw",//类型
              });
              //停止新建任务
              that.showCreateTaskArea();
              // //获取空间数据
              // let geom = evt.feature.getGeometry();
              // if (geom instanceof Polygon) {
              //   let coords = geom.getCoordinates()[0];
              //   if(coords.length>0){
              //     let polygonWkt = "POLYGON((";
              //     for(let i=0;i<coords.length;i++){
              //       if(i>0){
              //         polygonWkt += ",";
              //       }
              //       let lonlat = coords[i];
              //       polygonWkt += lonlat[0]+" "+lonlat[1];
              //     }
              //     polygonWkt += "))";
              //   }
              // }else{//圆形
              //   geom = new fromCircle(geom);//圆转多边形，用于空间查询
              //   let coords = geom.getCoordinates()[0];
              //   if(coords.length>0){
              //     let polygonWkt = "POLYGON((";
              //     for(let i=0;i<coords.length;i++){
              //       if(i>0){
              //         polygonWkt += ",";
              //       }
              //       let lonlat = coords[i];
              //       polygonWkt += lonlat[0]+" "+lonlat[1];
              //     }
              //     polygonWkt += "))";
              //   }
              // }
            }else if(that.queryMapDrawType=="Point") {//抽样点
              evt.feature.setProperties({
                type: "sample",//类型
              });
              //停止新建抽样点
              that.showSamplePoint();
            }
          }
        });
      }

      //停止绘制--等震线贝塞尔曲线面
      function stopNewDrawInteraction() {
        //停止绘制
        if (that.draw) {
          that.map.removeInteraction(that.draw);
          that.draw = null;
        }
      }

      //开启绘制--等震线贝塞尔曲线面
      function startNewDrawInteraction(type,bool) {
        //停止拖拽
        stopDragInteraction();
        //停止修改--等震线贝塞尔曲线面
        stopNewModifyInteraction();
        //停止选择
        stopSelectInteraction();
        //停止绘制
        stopNewDrawInteraction();
        if(bool){//手绘线|手绘面
          that.draw = new Draw({
            source: that.source,
            type: type,
            snapTolerance: 20,
            freehand: true
          });
          that.map.addInteraction(that.draw);
        }else{//点|线|面|圆绘制
          that.draw = new Draw({
            source: that.source,
            type: type,
            snapTolerance: 20
          });
          that.map.addInteraction(that.draw);
        }
        let listener;
        //开始绘制事件
        that.draw.on('drawstart', function (evt) {
          listener = evt.feature.getGeometry().on('change', function (evt) {
            const geom = evt.target;
            if(that.pageType=='地震烈度图绘制页面') {
              if (that.queryMapDrawType.indexOf("BezierSplinePolygon")==0) {//绘制贝塞尔曲线面
                if (geom instanceof Polygon) {
                  let coords = geom.getCoordinates()[0];
                  //获取贝塞尔曲线面
                  that.getBezierSplinePolygon(coords,false,null,that.drawBezierSplinePolygonIntensity);
                }
              }
            }
          });
        });
        //完成绘制事件
        that.draw.on('drawend', function (evt) {
          if(that.pageType=='地震烈度图绘制页面'){
            if(that.queryMapDrawType.indexOf("BezierSplinePolygon")==0){//绘制贝塞尔曲线面
              evt.feature.setProperties({
                type:"draw",//类型
              });
              //获取空间数据
              let geom = evt.feature.getGeometry();
              if (geom instanceof Polygon) {
                let coords = geom.getCoordinates()[0];
                //获取贝塞尔曲线面
                that.getBezierSplinePolygon(coords,true,null,that.drawBezierSplinePolygonIntensity);
              }
            }
          }
          unByKey(listener);
        });
      }

      //停止绘制|修改|拖拽|选择--等震线贝塞尔曲线面
      function clearNewInteraction() {
        //停止拖拽
        stopDragInteraction();
        //停止修改--等震线贝塞尔曲线面
        stopNewModifyInteraction();
        //停止选择
        stopSelectInteraction();
        //停止绘制
        stopDrawInteraction();
      }

      //停止修改--等震线贝塞尔曲线面
      function stopNewModifyInteraction() {
        //停止修改
        if (that.modify) {
          that.map.removeInteraction(that.modify);
          that.modify = null;
          if(that.pageType=='地震烈度图绘制页面'){
            //获取绘制数据
            // that.getAllDrawGeomEmit();
          }
        }
      }

      //开启修改--等震线贝塞尔曲线面
      function startNewModifyInteraction() {
        //停止绘制
        stopDrawInteraction();
        //开启选择
        startSelectInteraction();
        //停止修改
        stopNewModifyInteraction();
        //开启修改
        that.modify = new Modify({
          features: that.select.getFeatures()
        });
        that.map.addInteraction(that.modify);
        that.modify.on('modifystart', function (evt) {
          console.log(evt)
          if(that.pageType=='地震烈度图绘制页面') {
            let type = evt.features.array_[0].values_.type;
            if (type=="drawBezierSplinePolygon") {//绘制贝塞尔曲线面
              let siId = evt.features.array_[0].values_.siId;
              let intensity = evt.features.array_[0].values_.intensity;
              evt.features.array_[0].values_.geometry.on('change', function (evt) {
                console.log("change");
                console.log(evt);
                const geom = evt.target;
                if (geom instanceof Polygon) {
                  let coords = geom.getCoordinates()[0];
                  //获取贝塞尔曲线面
                  that.getBezierSplinePolygon(coords,false,siId,intensity);
                }
              });
            }
          }
        })
        that.modify.on('modifyend', function (evt) {
          console.log(that.queryMapDrawType);
          console.log(evt);
          if(that.pageType=='地震烈度图绘制页面'){
            let type = evt.features.array_[0].values_.type;
            let selectFeatureCoor = evt.features.array_[0].values_.geometry.getCoordinates()
            if(type=="drawBezierSplinePolygon"){//绘制贝塞尔曲线面
              let siId = evt.features.array_[0].values_.siId;
              let intensity = evt.features.array_[0].values_.intensity;
              let coords = selectFeatureCoor[0];
              //获取贝塞尔曲线面
              that.getBezierSplinePolygon(coords,true,siId,intensity);
            }
          }
        })
      }

      //计算面积
      function getPolygonArea (polygon) {
        // 这里一定要给坐标，和地图坐标保持一致，否则面积不准
        const area = getArea(polygon, {projection: 'EPSG:4490'})
        let output = Math.round((area / 1000000) * 100) / 100;//平方公里
        return output;
      }

      ////////////////////////////////////////////////////////////////////测量工具箱
      //格式化距离
      function formatLength(line) {
        const length = getLength(line, {projection: 'EPSG:4490'});
        let output;
        if (length > 100) {
          output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
        } else {
          output = Math.round(length * 100) / 100 + ' ' + 'm';
        }
        return output;
      }

      //格式化面积
      function formatArea(polygon) {
        const area = getArea(polygon, {projection: 'EPSG:4490'});
        let output;
        if (area > 10000) {
          output = Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>';
        } else {
          output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>';
        }
        return output;
      }

      //创建新的提示tip
      function createHelpTooltip() {
        if (that.helpTooltipElement!=null) {
          that.helpTooltipElement.parentNode.removeChild(that.helpTooltipElement);
        }
        that.helpTooltipElement = document.createElement('div');
        that.helpTooltipElement.className = 'ol-tooltip hidden';
        that.helpTooltip = new Overlay({
          element: that.helpTooltipElement,
          offset: [15, 0],
          positioning: 'center-left',
        });
        that.map.addOverlay(that.helpTooltip);
      }

      //创建新的测量提示
      function createMeasureTooltip() {
        if (that.measureTooltipElement!=null) {
          that.measureTooltipElement.parentNode.removeChild(that.measureTooltipElement);
        }
        that.measureTooltipElement = document.createElement('div');
        that.measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
        that.measureTooltip = new Overlay({
          element: that.measureTooltipElement,
          offset: [0, -15],
          positioning: 'bottom-center',
          stopEvent: false,
          insertFirst: false,
        });
        that.map.addOverlay(that.measureTooltip);
      }

      //开启测量工具
      function startMeasureInteraction(type) {
        //停止测量工具
        stopMeasureInteraction();

        console.log(type);
        //开启测量工具--绘制
        that.measure = new Draw({
          source: that.measureSource,
          type: type,
          style: new Style({
            fill: new Fill({
              color: 'rgba(255, 255, 255, 0.2)',
            }),
            stroke: new Stroke({
              color: 'rgba(0, 0, 0, 0.5)',
              lineDash: [10, 10],
              width: 2,
            }),
            image: new CircleStyle({
              radius: 5,
              stroke: new Stroke({
                color: 'rgba(0, 0, 0, 0.7)',
              }),
              fill: new Fill({
                color: 'rgba(255, 255, 255, 0.2)',
              }),
            }),
          }),
        });
        that.map.addInteraction(that.measure);

        //创建新的测量提示
        createMeasureTooltip();
        //创建新的提示tip
        createHelpTooltip();

        let listener;
        that.measure.on('drawstart', function (evt) {
          //设置sketch
          that.sketch = evt.feature;

          let tooltipCoord = evt.coordinate;

          listener = that.sketch.getGeometry().on('change', function (evt) {
            const geom = evt.target;
            let output;
            if (geom instanceof Polygon) {
              output = formatArea(geom);
              tooltipCoord = geom.getInteriorPoint().getCoordinates();
            } else if (geom instanceof LineString) {
              output = formatLength(geom);
              tooltipCoord = geom.getLastCoordinate();
            }
            that.measureTooltipElement.innerHTML = output;
            that.measureTooltip.setPosition(tooltipCoord);
          });
        });
        //完成测量绘制
        that.measure.on('drawend', function () {
          that.measureTooltipElement.className = 'ol-tooltip ol-tooltip-static';
          that.measureTooltip.setOffset([0, -7]);
          //添加到数组
          that.measureTooltipArray.push(that.helpTooltip);
          //添加到数组
          that.measureTooltipArray.push(that.measureTooltip);
          //清空sketch
          that.sketch = null;
          //清空tooltip
          that.measureTooltipElement = null;
          createMeasureTooltip();
          unByKey(listener);
        });
      }

      //停止测量工具
      function stopMeasureInteraction() {
        //停止绘制
        stopDrawInteraction();
        //停止测量工具
        if (that.measure) {
          that.map.removeInteraction(that.measure);
          that.measure = null;
          //隐藏提示tip
          that.helpTooltipElement.classList.add('hidden');
          //移除测量提示
          if(that.helpTooltip!=null){
            that.map.removeOverlay(that.helpTooltip);
          }
          if(that.measureTooltip!=null){
            that.map.removeOverlay(that.measureTooltip);
          }
        }
      }

      //清空测量结果
      function clearMeasureResult(){
        if(that.measureSource!=null){
          //清空测量结果
          that.measureSource.clear();
          //清空测量结果提示数组
          if(that.measureTooltipArray.length>0){
            for(let i=0;i<that.measureTooltipArray.length;i++){
              that.map.removeOverlay(that.measureTooltipArray[i]);
            }
            that.measureTooltipArray = [];
          }
        }
      }
    },
    getPolyonStyle(color){//多边形样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:color
        })
      });

      return style;
    },
    getPointStyle(){//点图标样式
      let style = new Style({
        image: new Icon({
          src: dingweiImg,
          anchor: [0.5, 1]
        }),
      });

      return style;
    },
    getLineStringStyle(color){//线样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//线
          width:2,//宽
          color:color
        })
      });

      return style;
    },
    //处理经纬度
    getLonLat(longitude,latitude){
      let lonlat = null;
      if(longitude!=null && latitude!=null && longitude!="" && latitude!=""){
        let lon = Number(longitude);
        let lat = Number(latitude);
        if(lon>0 && lon<180 && lat>0 && lat<90){
          lonlat = [lon,lat];
        }
      }

      return lonlat;
    },
    //是否开启地图圈选查询
    queryMapEvent(){
      if(this.map!=null){
        this.editGeomBool = false;
        if(this.queryMapDrawType=="Point"){
          //地图工具箱--开启点绘制
          this.setMapToolBox("Point");
        }else if(this.queryMapDrawType=="Polygon"){
          //地图工具箱--开启多边形绘制
          this.setMapToolBox("Polygon");
        }else if(this.queryMapDrawType=="Circle"){
          //地图工具箱--开启圆形绘制
          this.setMapToolBox("Circle");
        }else if(this.queryMapDrawType=="CircleRadius"){
          // //地图工具箱--开启圆心绘制
          // this.setMapToolBox("CircleRadius");
          // //根据开启圆形绘制
          // let meter = 1000;//米
          // let degree = meterToDegree(meter);
          // let circle = new Circle([116, 39], degree); // 用圆心和半径确定一个圆
          // // let polygon = new fromCircle(circle) // 得到一个多边形
          // let feature = new Feature({
          //   geometry: circle
          // });
          // this.source.addFeature(feature);
        }else if(this.queryMapDrawType=="StopDraw"){
          //地图工具箱--停止绘制
          this.setMapToolBox("StopDraw");
        }else if(this.queryMapDrawType=="Clear"){
          //地图工具箱--清空
          this.setMapToolBox("Clear");
        }else if(this.queryMapDrawType=="Select"){
          //地图工具箱--开启选择
          this.setMapToolBox("Select");
        }else if(this.queryMapDrawType.indexOf("BezierSplinePolygon")==0){
          //获取绘制烈度
          this.drawBezierSplinePolygonIntensity = this.queryMapDrawType.split("BezierSplinePolygon")[1];
          //地图工具箱--开启绘制贝塞尔曲线面
          this.setMapToolBox("BezierSplinePolygon");
        }else if(this.queryMapDrawType=="clearBezierSplinePolygon"){
          //地图工具箱--清空绘制贝塞尔曲线面
          this.setMapToolBox("clearBezierSplinePolygon");
        }else if(this.queryMapDrawType=="StopDrawBezierSplinePolygon"){
          //地图工具箱--停止绘制贝塞尔曲线面
          this.setMapToolBox("StopDrawBezierSplinePolygon");
        }
      }
    },
    //获取绘制数据
    getAllDrawGeomEmit(){
      let list = [];
      //获取全部绘制的空间数据
      let features = this.source.getFeatures();
      // console.log("获取绘制数据进行分布规律分析");
      // console.log(features);
      if(features!=null && features.length>0) {
        for (let i = 0; i < features.length; i++) {
          let feature = features[i];
          let geom = feature.getGeometry();
          if (geom instanceof Polygon) {//多边形
            let coords = geom.getCoordinates()[0];
            if(coords.length>0){
              let polygonWkt = "POLYGON((";
              for(let i=0;i<coords.length;i++){
                if(i>0){
                  polygonWkt += ",";
                }
                let lonlat = coords[i];
                polygonWkt += lonlat[0]+" "+lonlat[1];
              }
              polygonWkt += "))";
              list.push(polygonWkt);
            }
          }else if (geom instanceof Point) {
            //点
          }else if (geom instanceof LineString) {
            //线
          }else{//圆形
            geom = new fromCircle(geom);//圆转多边形，用于空间查询
            let coords = geom.getCoordinates()[0];
            if(coords.length>0){
              let polygonWkt = "POLYGON((";
              for(let i=0;i<coords.length;i++){
                if(i>0){
                  polygonWkt += ",";
                }
                let lonlat = coords[i];
                polygonWkt += lonlat[0]+" "+lonlat[1];
              }
              polygonWkt += "))";
              list.push(polygonWkt);
            }
          }
        }
      }
      // console.log(list);
      //地图圈选查询
      this.$emit("getAllDrawGeom",list);
    },
    //设置半径
    setCircleRadius(){
      if(this.selectFeatureType=="CircleDraw"){
        if(this.circleRadiusDialogBool){
          let meter = this.circleRadiusNum;//米
          if(!isNaN(meter) && Number(meter)>0){
            let degree = meterToDegree(Number(meter));
            this.selectFeature.getGeometry().setRadius(degree);
            this.circleRadiusDialogBool = false;
          }else{
            ElMessage.warning("请输入正数");
          }
        }else{
          let meter = degreeToMeter(this.selectFeature.getGeometry().getRadius());
          this.circleRadiusNum = meter.toFixed(2);//保留2位小数
          this.circleRadiusDialogBool = true;
        }
        //隐藏右键菜单窗口
        this.contextmenuLayer.setPosition(undefined);
      }
    },
    //修改区域
    editDrawGeom(){
      if(this.editGeomBool){
        this.editGeomBool = false;
        //地图工具箱--停止修改
        this.setMapToolBox('NotModify');
      }else{
        this.editGeomBool = true;
        this.restricTionSource = new WKT().readFeature(this.outAndInterRingDataSelf[4].geom)
        //地图工具箱--开启修改
        this.setMapToolBox('Modify');
      }
      //隐藏右键菜单窗口
      this.contextmenuLayer.setPosition(undefined);
    },
    //删除区域
    deleteDrawGeom(){
      if(this.selectFeatureType=="xzqh"){
        //行政区划
      }else{//地图圈选
        //隐藏右键菜单窗口
        this.contextmenuLayer.setPosition(undefined);
        //获取绘制数据
        // this.getAllDrawGeomEmit();
        //属性
        let temp = this.selectFeature.getProperties();
        if (temp.xstmId!=undefined) {
          let xstmId = temp.xstmId;
          //获取选中的要素空间数据
          this.$emit("createTaskArea",{type:"删除",xstmId:xstmId});
        }else if (temp.id!=undefined && temp.type=="sample" || temp.type=="taskSample") {//抽样点
          let id = temp.id;
          //获取选中的要素空间数据
          this.$emit("createSamplePoint",{type:"删除",id:id});
        }
        //移除要素
        this.source.removeFeature(this.selectFeature);
        this.selectFeature = null;
      }
    },
    getSelectPolyonStyle(){//选中要素样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(255,255,255,0.2)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:"rgba(30,144,255,1)"
        })
      });
      return style;
    },
    showSeismicInfluenceImport(){//导入地震影响场
      if(this.showSeismicInfluenceImportBool){
        this.showSeismicInfluenceImportBool = false;
        this.$emit("seismicInfluenceUpload",false);
      }else{
        this.showSeismicInfluenceImportBool = true;
        this.$emit("seismicInfluenceUpload",true);
      }
    },
    showDrawSeismicInfluence(){//制图
      if(this.showDrawSeismicInfluenceBool){
        this.showDrawSeismicInfluenceBool = false;
      }else{
        this.showDrawSeismicInfluenceBool = true;
        this.$emit("showDrawSeismicInfluence",true);
      }
    },
    showRemark(){//烈度说明
      if(this.showRemarkBool){
        this.showRemarkBool = false;
      }else{
        this.showRemarkBool = true;
        this.$emit("showRemark",true);
      }
    },
    showPrintImage(){//生成图件
      if(this.showPrintImageBool){
        this.showPrintImageBool = false;
      }else{
        this.showPrintImageBool = true;
        this.$emit("showPrintImage",true);
      }
    },
    showCreateTaskArea(){//新建任务（划定评估子区）
      if(this.showSamplePointBool){
        this.showSamplePoint();//停止新建抽样点
      }
      if(this.showCreateTaskAreaBool){
        this.showCreateTaskAreaBool = false;
        this.queryMapDrawType = "StopDraw";
        //地图工具箱--停止绘制
        this.setMapToolBox("StopDraw");
      }else{
        // this.showCreateTaskAreaBool = true;
        // this.queryMapDrawType = "Polygon";
        // //地图工具箱--开启多边形绘制
        // this.setMapToolBox("Polygon");
        //开启烈度图层选择
        this.$emit('openLayerSelect',true)
      }
    },
    showSamplePoint(){//新建抽样点
      if(this.showCreateTaskAreaBool){
        this.showCreateTaskArea();//停止新建任务（划定评估子区）
      }
      if(this.showSamplePointBool){
        this.showSamplePointBool = false;
        this.queryMapDrawType = "StopDraw";
        //地图工具箱--停止绘制
        this.setMapToolBox("StopDraw");
      }else{
        this.showSamplePointBool = true;
        this.queryMapDrawType = "Point";
        //地图工具箱--开启点绘制
        this.setMapToolBox("Point");
      }
    },
    //获取选中的要素空间数据新建|修改|查看任务
    createTaskArea(){
      if(this.selectFeature){
        let xstmId = "";
        let temp = this.selectFeature.getProperties();
        if (temp.xstmId!=undefined) {
          xstmId = temp.xstmId;
        }
        let geom = this.selectFeature.getGeometry();
        if (geom instanceof Polygon) {//多边形
          let coords = geom.getCoordinates()[0];
          if(coords.length>0){
            let polygonWkt = "POLYGON((";
            for(let i=0;i<coords.length;i++){
              if(i>0){
                polygonWkt += ",";
              }
              let lonlat = coords[i];
              polygonWkt += lonlat[0]+" "+lonlat[1];
            }
            polygonWkt += "))";
            //获取选中的要素空间数据
            this.$emit("createTaskArea",{type:"保存",xstmId:xstmId,geom:polygonWkt});
          }
        }else if(geom instanceof MultiPolygon2) {
          let coords = geom.getCoordinates()[0];
          let polygonWkt = "MULTIPOLYGON((";
          for(let i = 0;i < coords.length;i++) {
            let polygon = "(";
            for(let j = 0;j < coords[i].length;j++) {
              if(j>0){
                polygon += ",";
              }
              let lonlat = coords[i][j];
              polygon += lonlat[0]+" "+lonlat[1];
            }
            if(i == coords.length - 1) {
              polygonWkt += polygon + ')))'
            }else{
              polygonWkt += polygon + '),'
            }
          }
          this.$emit("createTaskArea",{type:"保存",xstmId:xstmId,geom:polygonWkt});
        }else if(geom instanceof LineString) {
          let polygonList = "POLYGON((";
          // for(let i = 0;i < this.outAndInterRingDataSelf[2].getCoordinates().length;i++) {
          //     polygonList += this.outAndInterRingDataSelf[2].getCoordinates()[i][0] + ' ' + this.outAndInterRingDataSelf[2].getCoordinates()[i][1] + ','
          // }
          for(let i = 0;i < this.lineStringList[0].length;i++) {
              polygonList += this.lineStringList[0][i][0] + ' ' + this.lineStringList[0][i][1] + ','
          }
          for(let i = 0;i < this.outAndInterRingDataSelf[0].geometry.coordinates.length;i++) {
              polygonList += this.outAndInterRingDataSelf[0].geometry.coordinates[i][0] + ' ' + this.outAndInterRingDataSelf[0].geometry.coordinates[i][1] + ','
          }
          // for(let i = 0;i < this.outAndInterRingDataSelf[3].getCoordinates().length;i++) {
          //     polygonList += this.outAndInterRingDataSelf[3].getCoordinates()[i][0] + ' ' + this.outAndInterRingDataSelf[3].getCoordinates()[i][1] + ','
          // }
          for(let i = 0;i < this.lineStringList[1].length;i++) {
              polygonList += this.lineStringList[1][i][0] + ' ' + this.lineStringList[1][i][1] + ','
          }
          for(let i = 0;i < this.outAndInterRingDataSelf[1].geometry.coordinates.length;i++) {
              polygonList += this.outAndInterRingDataSelf[1].geometry.coordinates[i][0] + ' ' + this.outAndInterRingDataSelf[1].geometry.coordinates[i][1] + ','
          }
          polygonList += this.outAndInterRingDataSelf[2].getCoordinates()[0][0] + ' ' + this.outAndInterRingDataSelf[2].getCoordinates()[0][1] + '))'
          let featuremap = new WKT().readFeature(polygonList)
          featuremap.setProperties({
              type:"draw",//类型
              xstmId: this.outAndInterRingDataSelf[4].xstmId
            });
          featuremap.setStyle(this.getPolyonStyle('blue'))
          this.createTaskDataLayer.getSource().addFeature(featuremap)
          this.$emit("createTaskArea",{type:"保存",xstmId:xstmId,geom:polygonList});
        }
      }
      //隐藏右键菜单窗口
      this.contextmenuLayer.setPosition(undefined);
    },
    //删除选中要素
    clearSelectFeature(){
      if(this.pageType=='地震烈度图绘制页面'){
        if(this.source!=null && this.selectFeature!=null){
          let temp = this.selectFeature.getProperties();
          if (temp.type == "draw" || temp.type == "sample") {//地图圈选|绘制抽样点
            this.source.removeFeature(this.selectFeature);
            this.selectFeature = null;
          }
        }
      }
    },
    //获取选中的要素空间数据新建|修改|查看抽样点
    createSamplePoint(){
      if(this.selectFeature){
        let id = "";
        let temp = this.selectFeature.getProperties();
        if (temp.id!=undefined) {
          id = temp.id;
        }
        let geom = this.selectFeature.getGeometry();
        if (geom instanceof Point) {//点
          let coords = geom.getCoordinates();
          if(coords.length==2){
            //获取选中的要素空间数据
            this.$emit("createSamplePoint",{type:"保存",id:id,lon:coords[0],lat:coords[1]});
          }
        }
      }
      //隐藏右键菜单窗口
      this.contextmenuLayer.setPosition(undefined);
    },
    showHideButtonType(type){//显示|隐藏按钮类型
      let oldType = this.showButtonTypeStr;
      this.showButtonTypeStr = type;
      if(oldType!=type){
        //关闭按钮
        if(oldType=="showRemark"){//烈度说明
          this.showRemark();
        }
        if(oldType=="showPrintImage"){//生成图件
          this.showPrintImage();
        }
        if(oldType=="showDrawSeismicInfluence"){//制图
          if(this.showDrawSeismicInfluenceBool){
            this.showDrawSeismicInfluenceBool = false;
          }
        }
      }
    },
    getBezierSplinePolygon(coords,bool,siId,intensity){//获取贝塞尔曲线面
      if(coords.length>3){
        this.source.clear();//清空
        this.drawInfluenceSource.clear();//清空
        let line = turf.lineString(coords);
        let curved = turf.bezierSpline(line);
        let featureTmp = new Feature({
          geometry: new LineString(curved.geometry.coordinates)
        });
        //获取贝塞尔曲线经纬度
        // let coordinates = this.getBezierCurveCoords(coords,bool);
        // let featureTmp = new Feature({
        //   geometry: new LineString(coordinates)
        // });
        //样式
        let style = this.getLineStringStyle("red");
        featureTmp.setStyle(style);
        //设置属性
        featureTmp.setProperties({
          type:"drawBezierSpline",
          coords:coords,
          siId:siId,
          intensity:intensity
        });
        //添加贝塞尔曲线
        this.drawInfluenceSource.addFeature(featureTmp);

        //临时绘制面
        let feature = new Feature({
          geometry: new Polygon([coords])
        });
        //样式
        let style1 = new Style({
          fill:new Fill({//填充样式
            color:"rgba(255,255,255,0.2)"
          }),
          stroke:new Stroke({//描绘
            width:2,//宽
            color:"rgb(0,153,255)"
          })
        });
        feature.setStyle(style1);

        //设置属性
        feature.setProperties({
          type:"drawBezierSplinePolygon",
          coords:coords,
          siId:siId,
          intensity:intensity
        });
        //添加贝塞尔曲线面
        this.drawInfluenceSource.addFeature(feature);
        if(bool==true && siId==null){//完成绘制
          this.$emit("getDrawInfluence",null);
          this.showDrawSeismicInfluenceBool = false;
        }
        console.log("完成绘制----");
        console.log(coords);
      }
    },
    //修改等震线
    editDrawInfluence(){
      if(this.editDrawInfluenceBool){
        this.editDrawInfluenceBool = false;
        //地图工具箱--停止修改--等震线贝塞尔曲线面
        this.setMapToolBox('StopNewModify');
      }else{
        this.editDrawInfluenceBool = true;
        let temp = this.selectFeature.getProperties();
        if(temp.type=="drawSeismicInfluence"){//已保存的烈度图数据
          let coords = [];
          let coordsStr = temp.coords;
          let tempArr = coordsStr.split(",");
          for(let i=0;i<tempArr.length;i++){
            let lonlat = tempArr[i].split(" ");
            let lon = Number(lonlat[0]);
            let lat = Number(lonlat[1]);
            coords.push([lon,lat]);
          }
          this.getBezierSplinePolygon(coords,false,temp.siId,temp.intensity);//获取贝塞尔曲线面
          //地图工具箱--开启修改--等震线贝塞尔曲线面
          this.setMapToolBox('NewModify');
        }else if(temp.type=="drawBezierSplinePolygon"){//正在绘制贝塞尔曲线面
          //地图工具箱--开启修改--等震线贝塞尔曲线面
          this.setMapToolBox('NewModify');
        }
      }
      //隐藏右键菜单窗口
      this.contextmenuLayer.setPosition(undefined);
      this.selectFeature = null;
    },
    //保存等震线
    saveDrawInfluence(){
      let features = this.drawInfluenceSource.getFeatures();
      if(features!=null && features.length>0) {
        for (let i = 0; i < features.length; i++) {
          let feature = features[i];
          let temp = feature.getProperties();
          if(temp.type=="drawBezierSpline"){//绘制曲线
            let geom = feature.getGeometry();
            if (geom instanceof LineString) {
              let list = geom.getCoordinates();
              this.editDrawInfluenceBool = false;
              //地图工具箱--停止修改--等震线贝塞尔曲线面
              this.setMapToolBox('StopNewModify');
              this.$emit("getDrawInfluence", {list: list, coords: temp.coords, siId: temp.siId, intensity:temp.intensity});
            }
            break;
          }
        }
      }
      //隐藏右键菜单窗口
      this.contextmenuLayer.setPosition(undefined);
      this.selectFeature = null;
    },
    //删除等震线
    deleteDrawInfluence(){
      let temp = this.selectFeature.getProperties();
      if(temp.type=="drawSeismicInfluence"){//已保存的烈度图数据
        this.$emit("deleteDrawInfluence", temp.siId);
      }else if(temp.type=="drawBezierSplinePolygon"){//正在绘制贝塞尔曲线面
        this.source.clear();//清空
        this.drawInfluenceSource.clear();//清空
        this.editDrawInfluenceBool = false;
        //地图工具箱--停止修改--等震线贝塞尔曲线面
        this.setMapToolBox('StopNewModify');
      }
      //隐藏右键菜单窗口
      this.contextmenuLayer.setPosition(undefined);
      this.selectFeature = null;
    },
    //获取贝塞尔曲线经纬度
    getBezierCurveCoords(coords,bool){
      let allCoordinates = [];
      //0,1,2,0
      if(coords.length>3){
        for(let i=0;i<(coords.length-1);i=i+2){
          let arrPoints = [];
          arrPoints.push(coords[i]);
          arrPoints.push(coords[i+1]);
          if(i==(coords.length-2)){
            arrPoints.push(coords[1]);
          }else{
            arrPoints.push(coords[i+2]);
          }
          console.log("arrPoints");
          console.log(coords);
          console.log(arrPoints);
          let line = turf.lineString(arrPoints);
          console.log(line);
          let arrbline = turf.bezierSpline(line);
          console.log(arrbline);
          let coordinates = arrbline.geometry.coordinates;
          allCoordinates = allCoordinates.concat(coordinates);
        }

        // coords.push(coords[1]);
        // let line = turf.lineString(coords);
        // console.log(line);
        // let arrbline = turf.bezierSpline(line);
        // console.log(arrbline);
        // let coordinates = arrbline.geometry.coordinates;

        // let line1 = turf.lineString([[126, -11], [129, -21]]);
        // let line2 = turf.lineString([[123, -18], [131, -14]]);
        // let intersects = turf.lineIntersect(line1, line2);
        // console.log(intersects);
        // let index = null;//第2个点序号
        // let coordsArr1 = [];//第1个点到第2个点的线段经纬度
        // for(let i=0;i<coordinates.length;i++){
        //   if(coordinates[i][0]==coords[0][0] && coordinates[i][1]==coords[0][1]){//第2个点
        //     index = i;
        //   }
        //   if(index==null){
        //     coordsArr1.push(coordinates[i]);
        //   }
        // }




        // allCoordinates = allCoordinates.concat(coordinates);


        // //最后1个点与第1个点
        // let arrPoints = [];
        // let startLonLat = coords[0];
        // let endLonLat = coords[coords.length-1];
        // let centerLon = (startLonLat[0] + endLonLat[0]) / 2;
        // let centerLat = (startLonLat[1] + endLonLat[1]) / 2;
        // arrPoints.push(endLonLat);
        // arrPoints.push([centerLon,centerLat]);//中点
        // arrPoints.push(startLonLat);
        // console.log("最后1个点与第1个点");
        // console.log(arrPoints);
        // let line = turf.lineString(arrPoints);
        // console.log(line);
        // let arrbline = turf.bezierSpline(line);
        // console.log(arrbline);
        // let coordinates = arrbline.geometry.coordinates;
        // allCoordinates = allCoordinates.concat(coordinates);
      }
      return allCoordinates;
    },
    //补全0
    completeDate(value) {
      return value < 10 ? "0" + value : value;
    },
    //获取当前时间，格式YYYY-MM-DD
    getFormatDay(date) {
      if (date == null) {
        date = new Date();
      }
      let char = "-";
      let day = date.getDate();
      let month = date.getMonth() + 1;//注意月份需要+1
      let year = date.getFullYear();
      //补全0，并拼接
      return year + char + this.completeDate(month) + char + this.completeDate(day);
    },
    //获取当前时间，格式YYYY-MM-DD HH:mm:ss
    getFormatTime(date) {
      if (date == null) {
        date = new Date();
      }
      let colon = ":";
      let h = date.getHours();
      let m = date.getMinutes();
      let s = date.getSeconds();
      //补全0，并拼接
      return this.getFormatDay(date) + " " + this.completeDate(h) + colon + this.completeDate(m) + colon + this.completeDate(s);
    }
  }
}

</script>

<style scoped lang="scss">
.init-spanBottom {
  border:0;
}
.new-contextmenu p {
  width:110px;cursor:pointer;padding:5px;margin-top: 5px;margin-bottom: 5px;
}
.new-contextmenu p:hover {
  background: rgba(14, 94, 180, 0.4);border: 1px solid #707070;
}
.new-contextmenu div {
  width:100%;
  border-bottom: 1px dashed white;
}
</style>